package com.xzwzz.kotlindemo

import com.alibaba.fastjson.JSONArray
import java.io.*
import java.util.ArrayList
import java.util.Objects
import java.util.Scanner
import java.io.IOException
import jdk.nashorn.internal.runtime.ScriptingFunctions.readLine
import java.io.InputStreamReader
import java.io.BufferedReader
import java.io.FileInputStream
import java.util.concurrent.Executors
import java.io.BufferedInputStream
import java.util.zip.ZipEntry
import java.io.File
import java.util.zip.ZipOutputStream
import java.io.FileOutputStream
import java.util.zip.CRC32
import java.util.zip.CheckedOutputStream
import java.io.FileNotFoundException


object QiniuRenameUtil {
    val system = "五四制"
    val executors = Executors.newScheduledThreadPool(5)
    @Throws(IOException::class)
    @JvmStatic
    fun main(args: Array<String>) {
        while (true) {
            println("请输入路径")
            val scanner = Scanner(System.`in`)
            val path = scanner.nextLine()
            val mainFile = File(path)
            if (mainFile.isFile) {
                println("请输入一个文件夹")
                return
            }
            println(mainFile.absolutePath)
            mainFile.listFiles().forEach {
                replace(it)
            }
//            replace(mainFile)

        }
    }

    //    /Users/xzwzz/Desktop/cache2
    val regex = Regex("-六三版-jpg|-六三版")

    private fun replace(file: File) {
        file.let {
            renameFolder(it)
            val s = regex.replace(it.name.replace("年级", ""), "-63")
            println(s)
            rename(it, s)
        }
    }

    private fun renameFolder(f: File) {
        val files = f.listFiles()
        if (files == null) {
            println("${f.absolutePath}为空")
            return
        }
        f.listFiles().forEachIndexed { index, file ->
            println("index $index 取名为${"${index + 1}.jpg"}  结果${rename(file, "${index + 1}.jpg")}")
        }
    }
//    /Users/xzwzz/Desktop/未命名文件夹

    fun rename(file: File?, newName: String): Boolean {
        // file is null then return false
        if (file == null) return false
        // file doesn't exist then return false
        if (!file.exists()) return false
        // the new name is space then return false
        if (isSpace(newName)) return false
        // the new name equals old name then return true
        if (newName == file.name) return true
        val newFile = File(file.parent + File.separator + newName)
        // the new name of file exists then return false
        return !newFile.exists() && file.renameTo(newFile)
    }

    private fun isSpace(s: String?): Boolean {
        if (s == null) return true
        var i = 0
        val len = s.length
        while (i < len) {
            if (!Character.isWhitespace(s[i])) {
                return false
            }
            ++i
        }
        return true
    }
}